<?php

namespace App\Http\Controllers\Home;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    //登陆
   public function loginFrom(){
   return view('home.login.loginForm');
   }
   public function login(Request $request){
    
       $request->validate([
           'account'=>'required',
           'password'=>'required'
       ],[
           'account.required'=>'账号不能为空',
           'password.required'=>'密码不能为空',
       ]);
//        dd($request->toArray());
       if (filter_var($request->account,FILTER_VALIDATE_EMAIL)){
           $data['email']=$request->account;
       }else{
           $data['phone']=$request->account;
       }
       $data['password']=$request->password;
//        dd($data);
       $res= auth()->attempt($data);
//       dd($res);
       if ($res){
           return redirect('/')->with('success','登录成功');
       }else{
           return back()->with('error','登录失败，重新登录');
       }
   }
   public function logout(){
   auth()->logout();
   return redirect('/')->with('success','退出登录成功');
   }
   //加载注册页面
    public function resignFrom(){
    return view('home.login.resignFrom');
    }
    //注册
    public function resign(Request $request){
    $request->validate([
        'name'=>'required',
        'email'=>'required',
        'phone'=>'required',
        'password'=>'required|confirmed'
    ],[
        'name.required'=>'昵称不能为空',
        'email.required'=>'邮箱不能为空',
        'phone.required'=>'手机号码不能为空',
        'password.required'=>'密码不能为空',
        'password.confirmed'=>'密码不一致',
    ]);
    $request['password']=bcrypt($request['password']);
    User::create($request->all());
    return redirect()->route('home.login.loginFrom')->with('success','注册成功');
    }
    //加载重置密码页面
    public function resetFrom(){
    return view('home.login.resetPassword');
    }
    //重置密码
    public function resetPassword(Request $request){
        $request->validate([
            'account'=>'required',
            'password'=>'required|confirmed',
        ],[
            'account.required'=>'账号不能为空',
            'password.required'=>'密码不能为空',
            'password.confirmed'=>'两次密码输入不一致'
        ]);
        if (filter_var($request->account,FILTER_VALIDATE_EMAIL)){
            $user=User::where('email',$request->account)->first();
        }else{
            $user=User::where('phone',$request->account)->first();
        }
        // 判断用户是否存在,如果存在,就改密码,如果不存在,就提示用户不存在该账号
        if($user){
            $user->password=bcrypt($request->password);
            $user->save();
            return redirect()->route('home.login.loginFrom')->with('success','密码重置成功,去登陆吧!!');
        }else{
            return back()->with('error','该账号不存在');
        }
        
        
    }
}
